package network.server.handler.UserHandler;

import common.model.Entity.VerificationCodeCache;
import module.auth.UserService;
import module.auth.impl.UserServiceImpl;
import network.protocol.Request;
import network.protocol.Response;
import network.server.RequestHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * 用户服务处理器，用于处理客户端发来的用户相关请求。
 * <p>
 * 支持的操作包括：
 * <ul>
 *     <li>Login - 用户登录</li>
 *     <li>Register - 用户注册</li>
 *     <li>SendEmail - 发送邮箱验证码</li>
 *     <li>FindPassword - 找回密码/重置密码</li>
 *     <li>ChangePassword - 修改密码</li>
 *     <li>CheckPassword - 验证邮箱验证码</li>
 * </ul>
 *
 * 该处理器会根据请求中的 "action" 字段判断具体操作，并调用 {@link UserService} 完成业务逻辑。
 */
public class UserServiceHandler implements RequestHandler {
    private final UserService userService;
    private static final Logger logger = LoggerFactory.getLogger(UserServiceHandler.class);

    /**
     * 默认构造函数，使用 {@link UserServiceImpl} 单例
     */
    public UserServiceHandler() {
        userService = UserServiceImpl.getInstance();
    }

    /**
     * 带参数构造函数，可自定义 UserService 实例
     *
     * @param userService 用户服务实例
     */
    public UserServiceHandler(UserService userService) {
        this.userService = userService;
    }

    /**
     * 根据请求 action 分发到具体处理方法
     *
     * @param req 客户端请求
     * @return 操作结果 {@link Response}
     */
    @Override
    public Response<?> handle(Request req) {
        String action = req.getAction();
        logger.info("到达UserServiceHandler");
        String[] splitAction = action.split("\\.");
        logger.info(splitAction[1]);
        return switch (splitAction[1]) {
            case "Login" -> handleLogin(req);
            case "Register" -> handleRegister(req);
            case "SendEmail" -> handleSendEmail(req);
            case "FindPassword" -> handleFindPassword(req);
            case "ChangePassword" -> handleChangePassword(req);
            case "CheckPassword" -> handleCheckPassword(req);
            default -> Response.error("不支持的操作类型");
        };
    }

    /**
     * 处理用户登录请求
     *
     * @param req 请求参数中应包含 username, password, sessionId
     * @return 登录结果
     */
    private Response<?> handleLogin(Request req) {
        Map<String, Object> params = req.getParams();
        String username = params.get("username").toString();
        String password = params.get("password").toString();
        String sessionId = params.get("sessionId").toString();
        return userService.doLogin(sessionId, username, password);
    }

    /**
     * 处理用户注册请求
     *
     * @param req 请求参数中应包含 username, password, role, Email, Phone, realName, Gender, Avatar
     * @return 注册结果
     */
    private Response<?> handleRegister(Request req) {
        Map<String, Object> params = req.getParams();
        String username = params.get("username").toString();
        String password = params.get("password").toString();
        Integer role = Integer.parseInt(params.get("role").toString());
        String email = params.get("Email").toString();
        String phone = params.get("Phone").toString();
        String realName = params.get("realName").toString();
        Boolean gender = Boolean.parseBoolean(params.get("Gender").toString());
        String avatar = params.get("Avatar").toString();

        return userService.doRegister(username, password, role, email, phone, realName,
                gender, avatar);
    }

    /**
     * 处理发送邮件请求（验证码）
     *
     * @param req 请求参数中应包含 email
     * @return 发送结果
     */
    private Response<?> handleSendEmail(Request req) {
        Map<String, Object> params = req.getParams();
        String email = params.get("email").toString();
        return userService.SendEmail(email);
    }

    /**
     * 处理找回密码请求
     *
     * @param req 请求参数中应包含 email, newPassword
     * @return 修改结果
     */
    private Response<?> handleFindPassword(Request req) {
        Map<String, Object> params = req.getParams();
        String email = params.get("email").toString();
        String newPassword = params.get("newPassword").toString();
        return userService.ChangePassword(email,newPassword);
    }

    /**
     * 处理修改密码请求
     *
     * @param req 请求参数中应包含 username, oldPassword, newPassword
     * @return 修改结果
     */
    private Response<?> handleChangePassword(Request req) {
        Map<String, Object> params = req.getParams();
        String username = params.get("username").toString();
        String oldPassword = params.get("oldPassword").toString();
        String newPassword = params.get("newPassword").toString();
        return userService.doChangePassword(username, oldPassword, newPassword);
    }

    /**
     * 处理校验验证码请求
     *
     * @param req 请求参数中应包含 password（用户输入验证码）, email
     * @return 校验结果
     */
    private Response<?> handleCheckPassword(Request req) {
        Map<String, Object> params = req.getParams();
        String password = params.get("password").toString();
        String email = params.get("email").toString();
        String storedCode = VerificationCodeCache.getCode(email);
        if (storedCode == null) {
            return Response.error("验证码已过期，请重新获取");
        }
        Response<?> result = userService.CheckPassword(password, storedCode);
        if (result.isSuccess()) {
            VerificationCodeCache.removeCode(email);
        }
        return result;
    }
}
